<template>
  <div class="login">
    <span class="close-btn" @click="$router.back()">
      <i class="iconicon-test iconfont"></i>
    </span>
    <h2 class="logo">
      <i class="iconnew iconfont"></i>
    </h2>
    <!-- 输入 用户、密码 -->
    <MyInput
      v-model="user.username"
      type="text"
      :rules="rules.username"
      msg="用户手机号校验不合法"
      placeholder="用户名或手机号"
    ></MyInput>
    <MyInput
      v-model="user.password"
      type="password"
      :rules="rules.password"
      msg="密码3-18位"
      placeholder="密码"
    ></MyInput>
    <!-- 注册账号 -->
    <div class="tips">
      没有账号？<router-link to="/register">去注册</router-link>
    </div>
    <!-- 按钮 -->
    <MyButton type="primary" @click="loginFn">登录</MyButton>
  </div>
</template>

<script>
// 引入复用组件
import MyButton from "../components/MyButton.vue";
import MyInput from "../components/MyInput.vue";
// 引入api接口
import { userLoginAPI } from "../apis/user"; //此处的userLoginAPI是一个对象，需要使用{}来获取
import { setItem } from "../utils/localData";

export default {
  data() {
    return {
      user: {
        username: "",
        password: "",
      },
      rules: {
        username: /^1\d{10}$|^[a-zA-Z]\w{2,10}$|^1\d{4,5}$/,
        password: /^[a-zA-Z0-9~!@#$%^&*()_+=]{3,18}$/,
      },
    };
  },
  components: {
    MyButton,
    MyInput,
  },
  methods: {
    getValueFn(val) {
      this.user.name = val;
    },
    async loginFn() {
      // 登录按钮点击时也需要用正则校验
      if (
        this.rules.username.test(this.user.username) &&
        this.rules.password.test(this.user.password)
      ) {
        // 校验通过就发送请求登录
        const res = await userLoginAPI({
          // 💥 请求接口参数的键名称，必须按接口文档要求来
          username: this.user.username,
          password: this.user.password,
        });
        console.log(res);
        const {
          message,
          data: { token },
        } = res.data;
        if (message === "登录成功") {
          this.$toast.success(message);
          // localStorage.setItem("heimatoutiao-token", token);
          setItem(token);
          this.$router.push({
            path: "/user",
            query: {
              id: res.data.data.user.id,
            },
          });
        } else {
          this.$toast.fail(message);
        }
      } else {
        this.$toast("用户名或密码校验失败");
        // alert("用户名或密码校验失败");
      }
    },
  },
};
</script>

<style lang="less" scoped>
.close-btn {
  position: fixed;
  left: 20px;
  top: 20px;
  .iconfont {
    font-size: 20px;
    color: #666;
  }
}
.logo {
  display: flex;
  justify-content: center;
  padding: 60px 0 20px;
  .iconfont {
    color: #d81e06;
    font-size: 120px;
  }
}
.tips {
  padding: 0 30px;
  text-align: right;
}
</style>
